<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="150px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="计划编号" prop="planNumber">
            <el-input v-model="form.planNumber" placeholder="请输入计划编号" :readonly="!(optType === 'add')"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划名称" prop="planName">
            <el-input v-model="form.planName" placeholder="请输入计划名称"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="开始日期" prop="planDate">
            <el-date-picker
              clearable
              v-model="form.planDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择计划开始日期"
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="截止日期" prop="materialDeadline">
            <el-date-picker
              clearable
              v-model="form.materialDeadline"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择计划截止日期"
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="申请人" prop="applyPersonName">
            <el-input v-model="form.applyPersonName" placeholder="请选择申请人" readonly>
              <el-button slot="append" @click="handleSelectUser" icon="el-icon-search"></el-button>
            </el-input>
            <UserSelect ref="userSelect" @onSelected="onUserSelected"></UserSelect>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="申请部门" prop="applyDepartment">
            <el-input v-model="form.applyDepartment" readonly>
            </el-input>

          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remarks">
        <el-input v-model="form.remarks" type="textarea" placeholder="请输入备注" style="width: 100%" maxlength="250"/>
      </el-form-item>
    </el-form>
    <!--横线组件纯纯为了页面好看-->
    <el-divider content-position="center">采购物料</el-divider>
    <el-table :data="addGoodsList" border>
      <el-table-column label="物料编号" align="center" prop="itemCode"/>
      <el-table-column label="物料名称" align="center" prop="itemName"/>
      <el-table-column label="规格型号" align="center" prop="specification"/>
      <el-table-column label="单位" align="center" prop="unitOfMeasure"/>
      <el-table-column label="分类" align="center" prop="itemTypeName"/>
      <el-table-column label="采购数量" align="center" prop="quantity">
        <div class="item" slot-scope="scope">
          <el-input-number
            v-model="scope.row.quantity"
            controls-position="right"
            :min="scope.row.quantity"
            :max="90000000000"
            size="mini"
            style="width:130px"
          />
        </div>
      </el-table-column>
    </el-table>

    <div slot="footer" style="text-align:center;margin-top: 20px;">
      <el-button type="primary" @click="submitForm">保存采购计划</el-button>
      <el-button type="primary" @click="cancel">返 回</el-button>
    </div>
  </div>
</template>

<script>
import {addPlan} from "@/api/mes/cg/plan";
import {getType} from "@/api/mes/md/excrete"
import {genCode} from "@/api/system/autocode/rule"
import {getUserProfile} from "@/api/system/user";
import UserSelect from "@/components/userSelect/single.vue";

export default {
  name: "PurchasePlan",
  components: {UserSelect},
  data() {
    return {
      autoGenFlag: false,
      optType: 'add',
      // 添加的商品信息表格数据
      addGoodsList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        planNumber: [
          {required: true, message: "计划编号不能为空", trigger: "blur"}
        ],
        planDate: [
          {required: true, message: "计划日期不能为空", trigger: "change"}
        ],
        materialDeadline: [
          {required: true, message: "物料截止日期不能为空", trigger: "change"}
        ]
      },
      user: {},
    };
  },
  created() {
    this.getExcreteItem(this.$route.params.id, '2');
    this.handleAutoGenChange(true);
    this.getUser();
  },
  methods: {
    // 取消按钮
    cancel() {
      const obj = {path: "/design/excretePurchase"};
      this.$tab.closeOpenPage(obj);
    },
    /** 新增提交按钮 */
    submitForm() {
      let that = this;
      this.$modal.confirm('是否确认保存采购计划？').then(function () {
        that.$refs["form"].validate(valid => {
          if (valid) {
            //判断是否添加商品
            if (that.addGoodsList.length === 0) {
              that.$modal.msgError("请添加商品");
              return;
            }
            if (that.addGoodsList.length !== 0) {
              for (let i = 0; i < that.addGoodsList.length; i++) {
                if (that.addGoodsList[i].quantity === null || that.addGoodsList[i].quantity === undefined) {
                  that.$modal.msgError("请填写采购数量");
                  return;
                }
                if (that.addGoodsList[i].quantity <= 0) {
                  that.$modal.msgError("请填写正确的采购数量");
                  return;
                }
              }
            }
            that.form.cgPurchasePlanDetails = that.addGoodsList;
            //调取新增接口
            addPlan(that.form).then(response => {
              that.$modal.msgSuccess("新增成功");
              that.cancel();
            });
          }
        })


      });
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode('PURCHASE_PLAN_CODE').then(response => {
          this.form.planNumber = response;
        });
      } else {
        this.form.planNumber = null;
      }
    },
    getExcreteItem(id, type) {
      getType(id, type).then(response => {
        this.form = {
          planNumber: null,
          planName: null,
          planDate: new Date().toISOString().split('T')[0],
          materialDeadline: null,
          remarks: null,
          estimatedCost: null,
          sourceDocId: id,
          sourceDocType: 'EXCRETE',
          vendorId: null,
          vendorName: null,
          paymentType: null,
          vendorCode: null,
          contact: null,
          contactTel: null,
          applyPersonId: null,
          applyPersonName: null,
          applyDepartment: null,
          applyDepartmentId: null,
        };
        this.resetForm("form");
        response.data.excreteItems.forEach(item => {
          this.addGoodsList.push({
            itemId: item.itemId,
            itemCode: item.itemCode,
            itemName: item.itemName,
            itemTypeName: item.itemTypeName,
            specification: item.specification,
            unitOfMeasure: item.unitOfMeasure,
            estimatedUnitPrice: 0,
            quantity: item.used,
            total: 0
          })
        })
      });
    },
    // 获取登录用户
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.form.applyPersonId = this.user.userId;
        this.form.applyPersonName = this.user.nickName;
        this.form.applyDepartment = this.user.dept.deptName;
        this.form.applyDepartmentId = this.user.dept.deptId;
      });
    },
    handleSelectUser() {
      this.$refs.userSelect.showFlag = true;
    },
    // 用户选择弹出框
    onUserSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.applyPersonName = obj.nickName;
        this.form.applyPersonId = obj.id;
        this.form.applyDepartment = obj.dept.deptName;
        this.form.applyDepartmentId = obj.dept.deptId;
      }
    },
  }
};
</script>

<style scoped>

</style>
